package com.bl.car.controller;

import com.bl.car.constants.StateConstant;
import com.bl.car.entity.User;
import com.bl.car.repositiy.UserRepository;
import com.bl.car.result.Result;
import com.bl.car.utils.SpringSessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 用户前端接口
 *
 * @author zhx
 * @create 2017-11-16 13:42
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    //注册

    @PostMapping("/register")
    public Result<String> register(@RequestParam("userName") String userName,@RequestParam("pwd") String pwd,HttpSession session){
        User userByUsername = userRepository.getUserByUsername(userName);

        if(userByUsername != null){
            return Result.error("用户名已被注册!");
        }

        //判断非空
        User user = new User();
        user.setUsername(userName);
        user.setPwd(pwd);
        user.setIsEffect(StateConstant.USER_NONE);
        user.setType(StateConstant.USER_NONE);
        User save = userRepository.save(user);
        SpringSessionUtil.setSession(session, save);

        return Result.ok(save);
    }

    //登录

    @PostMapping("/login")
    public Result<User> login(@RequestParam("userName") String userName,@RequestParam("pwd") String pwd,HttpSession session){
        //判断非空
        User userByUsername = userRepository.getUserByUsername(userName);

        if(userByUsername == null){
            return Result.error("用户名错误");
        }

        if(userByUsername.getPwd().equals(pwd)){
            SpringSessionUtil.setSession(session, userByUsername);
            return Result.ok(userByUsername);
        }else{
            return Result.error("密码错误!");
        }
    }


    //验证
    @PostMapping("/getCheck")
    public Result<String> getCheck(@RequestParam("type") String type,HttpSession session){

        User tmpUser = SpringSessionUtil.getSession(session);




        return Result.ok("已提交审核!");
    }


    //重新获取用户信息

    @PostMapping("/getUserInfo")
    public Result<User> getUserInfo(HttpSession session){
        User tmpUser = SpringSessionUtil.getSession(session);
        return Result.ok(tmpUser);
    }

    //注销
    @PostMapping("/loginOut")
    public Result<String> loginOut(HttpSession session){

        session.removeAttribute(SpringSessionUtil.USER);

        return Result.ok("");
    }



}
